using Dapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.PurchasingManagement.PurchaseOrders;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.PurchasingManagement.PurchaseArrivalNotes;
using RBAC.Read.Api.Application.Dto.ERP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace RBAC.Read.Api.Application.Handler.ERP.PurchasingManagement.PurchaseArrivalNotes
{
    /// <summary>
    /// 采购到货单主表列表（分页+条件）
    /// </summary>
    public class GetArrivalNotesListHandler : IRequestHandler<GetArrivalNotesListCommand, APIPaging<ArrivalNoteListDto>>
    {
        private readonly IBaseRepository<ArrivalOrderInfo> _repo;
        private readonly ILogger<GetArrivalNotesListHandler> _logger;

        public GetArrivalNotesListHandler(
            IBaseRepository<ArrivalOrderInfo> repo,
            ILogger<GetArrivalNotesListHandler> logger)
        {
            _repo = repo;
            _logger = logger;
        }

        public Task<APIPaging<ArrivalNoteListDto>> Handle(GetArrivalNotesListCommand request, CancellationToken cancellationToken)
        {
            var res = new APIPaging<ArrivalNoteListDto>();
            try
            {
                // 基础查询 + 正确的供应商联表（Supplier.Id 为 long，而 ArrivalOrderInfo.SupplierId 为 string，需要转换）
                var fromSql = " FROM ArrivalOrderInfo a LEFT JOIN Supplier s ON a.SupplierId = CAST(s.Id AS CHAR) AND s.IsDeleted = 0 WHERE a.IsDeleted = 0";
                var whereParts = new List<string>();
                var param = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(request.DocCode))
                {
                    whereParts.Add("a.DocCode LIKE @DocCode");
                    param.Add("DocCode", $"%{request.DocCode}%");
                }
                if (!string.IsNullOrWhiteSpace(request.SupplierId))
                {
                    whereParts.Add("a.SupplierId = @SupplierId");
                    param.Add("SupplierId", request.SupplierId);
                }
                if (!string.IsNullOrWhiteSpace(request.DocStatus))
                {
                    whereParts.Add("a.DocStatus = @DocStatus");
                    param.Add("DocStatus", request.DocStatus);
                }
                // 暂不支持按供应商名称过滤（缺少可靠的供应商表名/字段）。
                if (request.DocDateStart.HasValue)
                {
                    whereParts.Add("a.DocDate >= @DocDateStart");
                    param.Add("DocDateStart", request.DocDateStart.Value.Date);
                }
                if (request.DocDateEnd.HasValue)
                {
                    whereParts.Add("a.DocDate < @DocDateEnd");
                    param.Add("DocDateEnd", request.DocDateEnd.Value.Date.AddDays(1));
                }

                var whereSql = whereParts.Count > 0 ? (" AND " + string.Join(" AND ", whereParts)) : string.Empty;

                // count
                var countSql = "SELECT COUNT(1)" + fromSql + whereSql;
                var total = _repo.Query<int>(countSql, param).FirstOrDefault();

                res.TotalCount = total;
                res.Code = APIEnums.Success;
                res.Msg = "获取采购到货单主表成功";

                if (total == 0)
                {
                    res.PageDatas = new List<ArrivalNoteListDto>();
                    return Task.FromResult(res);
                }

                // data
                var pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
                var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;
                var offset = (pageIndex - 1) * pageSize;
                if (offset < 0) offset = 0;
                param.Add("Offset", offset);
                param.Add("PageSize", pageSize);

                var dataSql = @"SELECT 
                                    a.Id,
                                    a.DocCode,
                                    a.BizType,
                                    a.PurchaseOrderNo,
                                    a.DeliveryNote,
                                    a.DocDate,
                                    a.Operator,
                                    a.SupplierId,
                                    s.Supplier_Name AS SupplierName,
                                    a.DocStatus,
                                    a.Auditor,
                                    a.Warehouse,
                                    a.BizStatus,
                                    a.AuditDate,
                                    a.Progress,
                                    a.Remark
                                " + fromSql + whereSql + @"
                                ORDER BY a.Id DESC
                                LIMIT @Offset, @PageSize";

                var rows = _repo.Query<ArrivalNoteListDto>(dataSql, param).ToList();
                res.PageDatas = rows;
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Error;
                res.Msg = "获取采购到货单主表失败";
                _logger.LogError(ex, "获取采购到货单主表失败: {Message}", ex.Message);
            }

            return Task.FromResult(res);
        }
    }
}
